<?php


namespace app\index\controller;


use think\App;
use think\Controller;
use think\facade\Cache;

class Vcode extends Controller
{

    public $width;     //定义宽度
    private $height;    //定义高度
    private $num;       //定义数量
    private $code;      //定义验证码
    private $img;       //定义图像资源

    #   构造方法（三个参数）
    public function __construct($width = 180,$height = 60,$num = 4)
    {
        $this->width = $width;
        $this->height = $height;
        $this->num = $num;
        $this->createCode();        //调用自己设置的私有函数
        Cache::set('Code',$this->code,60*60*24);
    }

    #   生成验证码字符串
    private function createCode(){
        $codes = "3456789qwertyuiopasdfghjklzxcvbnm";
        for ($i = 0 ; $i < $this->num ; $i++){
            $this->code .= $codes[rand(0,strlen($codes) - 1)];
        }
        return $this->code;
    }

    #   输出图像
    public function outImg(){
        //  创建背景（颜色，大小，边框）
        $this->createBack();
        //  画字（大小，字体颜色，倾斜）
        $this->outString();
        //  干扰元素
        $this->setDisturb();
        //  输出图像
        $this->printImg();
    }

    #   创建背景
    private function createBack(){
        //  创建资源    imagecreatetruecolor（生成一个真色彩image）
        $this->img = imagecreatetruecolor($this->width,$this->height);
        //  设置随机背景颜色
        $backColor = imagecolorallocate($this->img,rand(225,255),rand(225,255),rand(225,255));
        //  设置背景填充
        imagefill($this->img,0,0,$backColor);

        //  设置边框
        $borderColor = imagecolorallocate($this->img,0,0,0);
        imagerectangle($this->img,0,0,$this->width - 1,$this->height - 1,$borderColor);
    }

    #   输出字符串
    private function outString(){
        for ($i = 0 ; $i < $this->num ; $i++){
            $color = imagecolorallocate($this->img,rand(0,128),rand(0,128),rand(0,128));
            $fontsize = 5;
            $x = 3+($this->width/$this->num) * $i;
            $y = rand(0,imagefontheight($fontsize) - 3);

            imagechar($this->img,$fontsize,$x,$y,$this->code[$i],$color);
        }
    }

    #   设置干扰
    private function setDisturb(){
        //  画圆点
        for ($i = 0 ; $i < 100 ; $i++){
            $color = imagecolorallocate($this->img,rand(0,255),rand(0,255),rand(0,255));
            imagesetpixel($this->img,rand(1,$this->width-2),rand(1,$this->height-2),$color);
        }

        //  画线条
        for ($i = 0 ; $i < 10 ; $i++){
            $color = imagecolorallocate($this->img,rand(0,255),rand(0,255),rand(0,255));
            imagearc($this->img,rand(-10,$this->width+10),rand(-10,$this->height+10),rand(30,300),rand(30,300),55,44,$color);
        }
    }

    #   输出图像
    private function printImg(){
        header("content-type:image/png");
        imagepng($this->img);
    }

    #   用于自动销毁图像资源
    function __destruct()
    {
        imagedestroy($this->img);
    }
}